<?php

// +----------------------------------------------------------------------
// | Mcake
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://121.43.104.7 All rights reserved.
// +----------------------------------------------------------------------
// | Author: allen.qiang@fistforward.com
// +----------------------------------------------------------------------

/**
 * 冰包扫描ajax类
 * @package  ajax
 * @subpackage  backend
 * @author   allen.qiang@fistforward.com
 */
//加载订单商品查询类
//quanli_include('module/base/bill/billSearch.class.php');

//加载订单商品生产表查询类
quanli_include('module/base/bill/billGoodsProduct.class.php');

//查询配送站类
//quanli_require('module/base/system/sysDistribution.class.php');

//查询配送员类
//quanli_require('module/base/system/sysDistributionTechnician.class.php');

//冰包标签生产类
quanli_require('module/base/production/icePackCode.class.php');

class ajax_icePackGoods {

    public function execute() {

        global $G_PGLOB;

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch ($_REQUEST['operFlg']) {

                case 1:
                    $this->searchGoods();      //统计查询
                    break;

                case 2:
                    $this->scanGoods();      //查询商品详情
                    break;

                case 3:
                    $this->searchScanList();      //查询已扫过的商品
                    break;

                case 4:
                    $this->printIcePackLabel();   //打印冰包标签
                    break;

                default:
                    $G_PGLOB->smarty->assign('msg', '参数错误，请审核后再操作');
                    $G_PGLOB->smarty->display('comm/error.tpl');

            }
        }
    }

    /**
     * 统计查询
     */
    private function searchGoods() {

        //实例化入库单类
        $billGoodsProduct = new billGoodsProduct();

        if(!isset($_REQUEST['formValues']['send_date']) || empty($_REQUEST['formValues']['send_date'])){
            returnJsonData('请选择配送日期','400');
        }

        if(!isset($_REQUEST['formValues']['cityID']) || empty($_REQUEST['formValues']['cityID'])){
            returnJsonData('请选择配送城市','400');
        }

        if(!isset($_REQUEST['formValues']['distribution_id']) || empty($_REQUEST['formValues']['distribution_id'])){
            returnJsonData('请选择配送站','400');
        }

        $_REQUEST['formValues']['G_DFD_SKU'] = "DFD";//是不是代付单跳流程查询

        //调用分组查询订单商品生产表方法
        $billGoods_array = $billGoodsProduct->searchbillGoodsProductGroup($_REQUEST['formValues']);

        if ($billGoods_array && $billGoods_array[0]['warehouse_num']>0) {
            returnJsonData('ok','200',$billGoods_array);
        }else{
            returnJsonData('未找到【已上车】订单商品数据','400');
        }

    }


    /**
     * 冰包扫描操作
     */
    private function scanGoods() {

        global $G_PGLOB;

        if(!isset($_REQUEST['bill_goods_no']) || empty($_REQUEST['bill_goods_no'])){
            returnJsonData('缺少参数','400');
        }

        if(!isset($_REQUEST['formValues']['send_date']) || empty($_REQUEST['formValues']['send_date'])){
            returnJsonData('请选择配送日期','400');
        }

        if(!isset($_REQUEST['formValues']['cityID']) || empty($_REQUEST['formValues']['cityID'])){
            returnJsonData('请选择配送城市','400');
        }

        if(!isset($_REQUEST['formValues']['distribution_id']) || empty($_REQUEST['formValues']['distribution_id'])){
            returnJsonData('请选择配送站','400');
        }

        //实例化订单商品查询类
        $billGoodsProduct = new billGoodsProduct();

        $bill_goods_no = trim($_REQUEST['bill_goods_no']);

        //订单商品流水号参数
        $arg_array = array(
            'bill_goods_no'=>$bill_goods_no
        );

        //调用查询订单商品表方法
        $billGoods = $billGoodsProduct->searchBillGoodsInfo( $arg_array );

        if( !$billGoods ){
        	returnJsonData('暂无该商品流水号[' .$_REQUEST['bill_goods_no']. ']订单商品数据','404');
        }

        $cityID = $_REQUEST['formValues']['cityID'];
        $distributionID = $_REQUEST['formValues']['distribution_id'];
        $sendDate = $_REQUEST['formValues']['send_date'];

        if($billGoods[0]['is_warehouse'] != 1){
            returnJsonData('尚未上车扫描，请取出订单[' .substr($_REQUEST['bill_goods_no'],-7,7). ']','404');
        }

        if($billGoods[0]['is_packScan'] == 1){
            returnJsonData('该商品流水号[' .$_REQUEST['bill_goods_no']. ']已装包扫描','404');
        }

        if($billGoods[0]['distribution_id'] != $_REQUEST['formValues']['distribution_id']){
            returnJsonData('不匹配装包站点，请取出订单[' .substr($_REQUEST['bill_goods_no'],-7,7). ']','400');
        }

        if($billGoods[0]['send_date'] != $sendDate){
            returnJsonData('配送日期不匹配，请取出订单[' .substr($_REQUEST['bill_goods_no'],-7,7). ']','500');
        }

        //实例化冰包标签类
        $icePackCode = new icePackCode();

        //获取冰包标签
        $icePackLabel = $icePackCode->getIcePackLabel($cityID,$distributionID);

        $data['bill_code'] = $billGoods[0]['bill_code'];
        $data['goods_name'] = $billGoods[0]['goods_name'];
        $data['site_name'] = $billGoods[0]['distribution_name'];
        $data['ice_label'] = $icePackLabel;

        try {

            //开启事务
            $G_PGLOB->DBCA->beginTransaction();

            $bill_goods_product = new entity('bill_goods_product');
            $bill_goods_product->bill_goods_no = $bill_goods_no;

            if($G_PGLOB->DBCA->fetch($bill_goods_product)){
                //$bill_goods_product->is_packScan = 1;
                $bill_goods_product->packScan_operator = $G_PGLOB->currentUserID;
                $bill_goods_product->packScan_time = date('Y-m-d H:i:s',time());
                $bill_goods_product->icePack_label = $icePackLabel;
                $rs = $G_PGLOB->DBCA->save($bill_goods_product);
            }

            //提交事务
            $G_PGLOB->DBCA->commit();

            if($rs){
                $sql = 'SELECT audio FROM sys_distribution WHERE distribution_id = ?';
                $row = $G_PGLOB->DBCA->stmt_query($sql,'i',$distributionID);
                $data['audio'] = $row[0]->audio;
                returnJsonData('ok',200,$data);
            }else{
                returnJsonData('系统错误，请与管理员联系',404);
            }


        } catch (Exception $e){

            //回滚事务
            $G_PGLOB->DBCA->rollBack();

            if ($e->getCode() > 0) {
                returnJsonData( $e->getMessage(),$e->getCode());
                return;
            } else {
                returnJsonData( '系统错误，请与管理员联系',500);
                return;
            }

        }

    }

    /**
     * 查询已扫过的商品
     */
    private function searchScanList(){

        global $G_PGLOB;

        if(!isset($_REQUEST['formValues']['send_date']) || empty($_REQUEST['formValues']['send_date'])){
            returnJsonData('请选择配送日期','400');
        }

        if(!isset($_REQUEST['formValues']['cityID']) || empty($_REQUEST['formValues']['cityID'])){
            returnJsonData('请选择配送城市','400');
        }

        if(!isset($_REQUEST['formValues']['distribution_id']) || empty($_REQUEST['formValues']['distribution_id'])){
            returnJsonData('请选择配送站','400');
        }

        $send_date = $_REQUEST['formValues']['send_date'];
        $cityID = $_REQUEST['formValues']['cityID'];
        $distributionID = $_REQUEST['formValues']['distribution_id'];

        //实例化冰包标签类
        $icePackCode = new icePackCode();

        //获取冰包标签
        $icePackLabel = $icePackCode->getIcePackLabel($cityID,$distributionID);

        $sql = 'SELECT bill_code,goods_name,distribution_name FROM bill_goods_product WHERE send_date = ? AND is_warehouse = 1 AND is_packScan = 0 AND cityID = ? AND distribution_id = ? AND icePack_label IS NOT NULL';

        //调用查询订单商品表方法
        $billGoodsProducts = $G_PGLOB->DBCA->stmt_query($sql,'sii',array($send_date,$cityID,$distributionID));

        if( !$billGoodsProducts ){

            returnJsonData('暂无扫描订单商品数据','404');

        }else{

            foreach($billGoodsProducts as $procuct){
                $data[] = array(
                    'bill_code'=> $procuct->bill_code,
                    'goods_name'=> $procuct->goods_name,
                    'site_name'=> $procuct->distribution_name,
                    'ice_label'=> $icePackLabel
                );
            }

            returnJsonData('ok','200',$data);

        }

    }

    private function printIcePackLabel(){

        global $G_PGLOB;

        if(!isset($_REQUEST['formValues']['send_date']) || empty($_REQUEST['formValues']['send_date'])){
            returnJsonData('请选择配送日期','400');
        }

        if(!isset($_REQUEST['formValues']['cityID']) || empty($_REQUEST['formValues']['cityID'])){
            returnJsonData('请选择配送城市','400');
        }

        if(!isset($_REQUEST['formValues']['distribution_id']) || empty($_REQUEST['formValues']['distribution_id'])){
            returnJsonData('请选择配送站','400');
        }

        //实例化冰包标签类
        $icePackCode = new icePackCode();

        $status = intval($_REQUEST['status']);
        //$send_date = trim($_REQUEST['formValues']['send_date']);
        $cityID = intval($_REQUEST['formValues']['cityID']);
        $distributionID = intval($_REQUEST['formValues']['distribution_id']);

        //获取标签
        $icePackLabel = $icePackCode->getIcePackLabel($cityID,$distributionID);

        if($status == 0){//重复打印，取上一个标签

            $data['label_code'] = $icePackLabel-1;
            $data['update_num'] = 0;

            returnJsonData('ok','200',$data);

        }else{//首次打印

            $sql = 'SELECT COUNT(UUID) AS num FROM bill_goods_product WHERE icePack_label = ?';

            $row = $G_PGLOB->DBCA->stmt_query($sql,'i',$icePackLabel);

            //判断是否扫描蛋糕
            if($row[0]->num>0){

                //$rs = 更新装包扫描状态(true) ? 更新标签 : false;

                $rs = $this->updateGoodsStatus($icePackLabel) ? $icePackCode->updateIcePackLabel($cityID,$distributionID) : false;

                if($rs){

                    $data['label_code'] = $icePackLabel;
                    $data['update_num'] = $row[0]->num;

                    returnJsonData('ok','200',$data);
                }else{
                    returnJsonData('更新标签失败，请稍后再试！','400');
                }

            }else{
                returnJsonData('尚未扫描蛋糕！','400');
            }
        }

    }

    private function updateGoodsStatus($icePackLabel){

        global $G_PGLOB;

        $sql = 'SELECT bill_goods_no,packScan_operator,packScan_time FROM bill_goods_product WHERE icePack_label = ?';

        $rows = $G_PGLOB->DBCA->stmt_query($sql,'i',$icePackLabel);

        if(count($rows)>0){

            //事务开始
            $G_PGLOB->DBCA->beginTransaction();

            try {

                foreach($rows as $item){

                    //更新装包扫描：0、未装包 1、已装包
                    $update_sql = 'UPDATE bill_goods_product SET is_packScan = 1 WHERE bill_goods_no='.$item->bill_goods_no;

                    $G_PGLOB->DBCA->stmt_query($update_sql);

                    //更新订单商品表
                    $updateBillGoodsSql = 'UPDATE bill_goods SET is_packScan = 1 , packScan_operator = ? , packScan_time = ? , icePack_label = ? WHERE bill_goods_no='.$item->bill_goods_no;

                    $G_PGLOB->DBCA->stmt_query($updateBillGoodsSql,'ssi',array($item->packScan_operator,$item->packScan_time,$icePackLabel));

                }

                //事务提交
                $G_PGLOB->DBCA->commit();

                return true;

             } catch( Exception $ex ) {

                //实物回滚
                $G_PGLOB->DBCA->rollBack();

                return false;
            }

        }else{
            return false;
        }

    }

}
